package com.disease.chronic.Component;

import com.disease.chronic.Config.HttpSessionConfig;
import com.disease.chronic.Global.Result;
import com.disease.chronic.Service.DeviceService;
import com.disease.chronic.pojo.Device;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.Setter;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


//用来控制设备的上下线状态
@Component
@ServerEndpoint(value = "/device/status/{id}",configurator = HttpSessionConfig.class)
public class DeviceStatusWebSocket {

    String username;

    private static final ConcurrentHashMap<String, Session> sessionPoll = new ConcurrentHashMap<>();

    DeviceService deviceService;

    @Setter
    private static ApplicationContext applicationContext;

    @OnOpen
    public void onopen(Session session, @PathParam("id") String id) throws IOException {

        username = id;
        sessionPoll.put(id,session);

        deviceService = applicationContext.getBean(DeviceService.class);

        List<Device> devices = (List<Device>) deviceService.getDevices(id).getData();
        for(Device device:devices){
            setStatus(device.getUsername(),device.getName(),device.getStatus());
        }
    }

    static public void setStatus(String username,String deviceName,Integer status) throws IOException {
        if(sessionPoll.get(username)!=null)
            sessionPoll.get(username).getBasicRemote().sendText(deviceName+","+status);
    }

    @OnClose
    public void onClose(){
        sessionPoll.remove(username);
    }
}
